<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">{{ total }}</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" width="200" prop="staffPhoto">
            <template #default="{row}">
              <img
                v-fiximg="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="width:180px;height:120px;"
                alt=""
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployee" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" align="center" sortable="">
            <template #default="obj">
              {{ obj.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" align="center">
            <template #default="obj">
              <el-switch v-model="obj.row.enableState" :active-value="1" :inactive-value="2" disabled />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="obj">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${obj.row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showAssignRloe(obj.row.id)">角色</el-button>
              <el-button v-if="checkPermission('delEmployee')" type="text" size="small" @click="deleteEmployee(obj.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :page-size="pageConfing.size" :total="total" @current-change="currentChange" />
        </el-row>
      </el-card>
      <addEmployee :show-dialog.sync="showDialog" />
      <el-dialog title="二维码" :visible="isShowCode" @close="isShowCode = false">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <assign-role
        ref="assingRole"
        :is-show-role-dialog.sync="isShowAssignRloe"
      />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EnumEmployee from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import addEmployee from './components/add-employee'
import QRCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  components: { addEmployee, AssignRole },
  data() {
    return {
      isShowAssignRloe: false,
      isShowCode: false,
      showDialog: false,
      loading: false,
      pageConfing: {
        page: 1, // 当前页码
        size: 5
      },
      total: 0, // 总数
      employeeList: [],
      zidian: {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment'
      }
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 导出
    async exportExcel() {
      // 获取员工数据
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      // console.log(rows)
      // 数据装换
      const data = rows.map(userObj => {
        return this.objToArray(userObj)
      })
      const header = Object.keys(this.zidian)
      // 生成 excel
      export_json_to_excel({
        header,
        data
      })
    },
    objToArray(userObj) {
      const userArray = []
      for (const key in this.zidian) {
        const enKey = this.zidian[key]
        const value = userObj[enKey]
        if (enKey === 'formOfEmployment') {
          const obj = EnumEmployee.hireType.find(item => Number(item.id) === Number(value))
          userArray.push(obj ? obj.value : '未知')
        } else if (enKey === 'timeOfEntry') {
          userArray.push(formatDate(value))
        } else {
          userArray.push(value)
        }
      }
      console.log(userArray)
      // 转换逻辑
      return userArray
    },
    // 页面切换
    currentChange(newPage) {
      this.pageConfing.page = newPage
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.pageConfing)
      this.total = total
      // 本地数据库没有 enableState 属性， 可以考虑获取数据是手动造假
      this.employeeList = rows.map(user => {
        const state = Math.round(Math.random())
        return {
          ...user,
          enableState: user.enableState || Number(state)
        }
      })
      this.loading = false
    },
    // 应聘形式
    formatEmployee(row, col, cellval) {
      const obj = EnumEmployee.hireType.find(item => item.id === cellval)
      return obj ? obj.value : '未知'
    },
    // 删除员工
    async deleteEmployee(id) {
      try {
        await this.$confirm('您确定要删除该员工吗')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除员工成功')
        if (this.employeeList.length === 1 && this.pageConfing.page > 1) {
          this.pageConfing.page--
        }
      } catch (error) { console.log(error) }
    },
    // 二维码的生成
    showCode(url) {
      if (url) {
        this.isShowCode = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myCanvas, url, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    // 角色分配
    async showAssignRloe(id) {
      await this.$refs.assingRole.getCheckList(id)
      this.isShowAssignRloe = true
    }
  }
}
</script>

<style>

</style>
